#include "DHTesp.h"
#include "u8g2_font_t4.h"
#include "mqtt.h"
#include "rgb.h"

const String show_header = "章一砚 31801146";

DHTesp dht;
bool readDHT11(int delay_parm);
void callback_rgb(char *topic, byte *payload, unsigned int length);
void setup(void)
{
  Serial.begin(115200);
  // String thisBoard = ARDUINO_BOARD;
  // Serial.println(thisBoard);
  Serial.println(show_header);

  dht.setup(5, DHTesp::DHT11);

  u8g2.begin();
  u8g2.enableUTF8Print(); /* enable UTF8 support for the Arduino print() function */

  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback_rgb);

  RGB_init();
}

void loop(void)
{
  if (!client.connected())
  {
    reconnect();
  }
  client.loop();

  /* 获取温湿度数据到全局变量 并且生成打印用Char[] */
  char line_1[20];
  char line_2[20];
  if (readDHT11(500))
  {
    sprintf(line_1, "温度: %.1f ℃", dht.getTemperature());
    sprintf(line_2, "湿度: %.1f %%", dht.getHumidity());
    pub_dht(dht.getTemperature(), dht.getHumidity());
  }
  else
  {
    sprintf(line_1, "温度: ... ℃");
    sprintf(line_2, "湿度: ... %%");
  }

  /* 串口打印温湿度信息 */
  // Serial.println(String(line_1));
  // Serial.println(String(line_2));
  // Serial.println(" ");

  /* u8g2 渲染数据到 OLED 显示屏 */
  u8g2.setFont(u8g2_font_t4);
  u8g2.setFontDirection(0);
  u8g2.clearBuffer();
  u8g2.setCursor(0, 20);
  u8g2.print(show_header);
  u8g2.setCursor(0, 40);
  u8g2.print(line_1);
  u8g2.setCursor(0, 60);
  u8g2.print(line_2);
  u8g2.sendBuffer();
}
bool readDHT11(int delay_parm)
{
  bool out;
  delay(dht.getMinimumSamplingPeriod());
  out = (dht.getStatusString() == "OK");
  delay(delay_parm);
  return out;
}
void callback_rgb(char *topic, byte *payload, unsigned int length)
{
  mqtt_callback(topic, payload, length);
  if (strcmp(topic, "ZUCC-ZYY/rgb") == 0)
  {
    int parm[3];
    prase_rgb(payload, parm);
    Serial.print("R:");
    Serial.println(parm[0]);
    Serial.print("G:");
    Serial.println(parm[1]);
    Serial.print("B:");
    Serial.println(parm[2]);
    RGB_show(parm[0], parm[1], parm[2]);
  }
}